<?php

namespace api\modules\v1\forms\dingtalk;

use Yii;
use yii\base\Model;
use common\models\member\Member;

/**
 *
 * Class LoginForm
 * @package api\modules\v1\forms\dingtalk
 */
class DingtalkForm extends Model
{
    /**
     * 钉钉unionid
     *
     * @var
     */
    public $ding_unionid;

    /**
     * 钉钉openid
     *
     * @var
     */
    public $ding_openid;

    /**
     * 用户信息
     *
     * @var
     */
    protected $member;


    public function rules()
    {
        return [
            // 参数验证
            [['ding_unionid'], 'required', 'message' => '{attribute}不能为空', 'on' => ['bind']],

            [['ding_unionid'], 'checkDingUnionid', 'skipOnEmpty' => false, 'on' => ['bind']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 绑定钉钉
        $scenarios['bind'] = ['ding_unionid', 'ding_openid'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'ding_unionid' => 'ding_unionid',
            'ding_openid' => 'ding_openid',
        ];
    }

    /**
     * 检验用户UID
     *
     * @param $attribute
     * @return bool
     */
    public function checkDingUnionid($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $member = $this->getMember();
        if (empty($member)) {
            $this->addError($attribute, '用户不存在');
            return true;
        }

        if ($member->status != Member::STATUS_ENABLE) {
            $this->addError($attribute, '账户异常');
            return true;
        }

        if ($member->ding_unionid) {
            $this->addError($attribute, '用户已绑定');
            return true;
        }

        $otherMember = Yii::$app->services->member->findInfo(['ding_unionid' => $this->ding_unionid]);
        if ($otherMember) {
            $this->addError($attribute, '账号已被其他用户绑定，无法操作');
            return true;
        }
    }

    /**
     * 获取用户信息
     *
     * @return Member|null
     */
    public function getMember()
    {
        if (empty($this->member)) {
            $this->member = Yii::$app->services->member->findById(Yii::$app->user->identity->member_id);
        }

        return $this->member;
    }
}
